<template>
  <div>
    <el-dialog
      :title="addDeptsForm.id ? '编辑部门' : '新增部门'"
      :visible="visible"
      width="50%"
      @close="onDialgClose"
    >
      <!-- 绑定整个表单数据 -->
      <el-form ref="form" :model="addDeptsForm" :rules="addDeptsFormRules" label-width="100px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="addDeptsForm.name" placeholder="1-10位" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="addDeptsForm.code" placeholder="1-10位" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select v-model="addDeptsForm.manager" placeholder="请选择" @focus="getDeptsManager">
            <el-option
              v-for="item in deptsManager"
              :key="item.value"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="addDeptsForm.introduce" placeholder="1-50位" />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="$emit('input', false)">取 消</el-button>
        <el-button type="primary" @click="onSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getEmploteesListSimple } from '@/api/employees.js'
import { getDepartmentsList, addDepartments, getDepartmentsById, editDepartmentsById } from '@/api/departments.js'
export default {
  model: {
    prop: 'visible'
  },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    node: {
      type: Object,
      required: true
    }
  },

  data() {
    // 校验部门名称是否存在
    const validDeptName = async(rule, value, callback) => {
      let flag = false
      if (this.addDeptsForm.id) {
        // 编辑
        // 获取到所有的部门
        const res = await getDepartmentsList()
        // 筛选到同级别的部门，并且排除自己
        const newArr = res.depts.filter(item => item.pid === this.node.id && item.id !== this.node.id)
        // 根据同级别部门是否有重名
        flag = newArr.some(item => item.name === value)
      } else {
        // 新增
        if (!this.node.children) return callback()
        flag = this.node.children.some(item => item.name === value)
      }
      if (flag) {
        callback(new Error('不允许部门名称为' + value))
      } else {
        callback()
      }
    }
    // 校验部门编码是否存在
    const validDeptCode = async(rule, value, callback) => {
      // 返回的数据 list 不是tree
      const res = await getDepartmentsList()
      let flag = false
      if (this.addDeptsForm.id) {
        // 编辑
        const newArr = res.depts.filter(item => item.code !== this.node.code)
        flag = newArr.some(item => item.code === value)
      } else {
        flag = res.depts.some(item => item.code === value)
      }
      // console.log(res)
      // console.log(value)
      if (flag) return callback(new Error('不允许部门编码为' + value))
      callback()
    }
    return {
      // 新增表单对象
      addDeptsForm: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      addDeptsFormRules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 10, message: '部门名称长度1-10位', trigger: 'blur' },
          { validator: validDeptName, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请输入部门负责人', trigger: 'blur' },
          { message: '部门负责人长度1-10位', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 50, message: '部门介绍长度1-50位', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 10, message: '部门编码长度1-10位', trigger: 'blur' },
          { validator: validDeptCode, trigger: 'blur' }
        ]
      },
      deptsManager: []
    }
  },

  created() {

  },

  methods: {
    // 对话框关闭
    onDialgClose() {
      this.$emit('input', false)
      this.$refs.form.resetFields() // resetFields文档提供的重置表单方法
      this.addDeptsForm = { // 重置不够彻底，添加的信息无法重置，需要手动再重置一次
        name: '',
        manager: '',
        introduce: '',
        code: ''
      }
    },
    // 部门负责人获取焦点
    async getDeptsManager() {
      const res = await getEmploteesListSimple()
      // console.log(res)
      this.deptsManager = res
    },
    // 点击确定
    async onSave() {
      if (this.addDeptsForm.id) {
        // 编辑
        try {
          await this.$refs.form.validate()
          await editDepartmentsById(this.addDeptsForm)
          this.$message.success('修改成功')
          this.onDialgClose() // 关闭弹层
          this.$emit('edit-success')
        } catch (err) {
          console.log(err)
        }
      } else {
        // 新增
        try {
          await this.$refs.form.validate()
          // 请求的pid 使用 node.id
          this.addDeptsForm.pid = this.node.id
          await addDepartments(this.addDeptsForm)
          this.$message.success('添加成功')
          this.onDialgClose() // 关闭弹层
          this.$emit('add-success')
        } catch (err) {
          console.log(err)
        }
      }
    },
    // 获取最新数据
    async getDeptsInfo(id) {
      console.log('获取最新的数据', id)
      const res = await getDepartmentsById(id)
      this.addDeptsForm = res
    }
  }
}
</script>

<style scoped lang='less'>

</style>
